package com.demo.controller;

import com.demo.constant.MessageConstant;
import com.demo.pojo.Student;
import com.demo.result.Result;
import com.demo.dto.UserLoginDTO;
import com.demo.pojo.User;
import com.demo.service.UserService;
import com.demo.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    /**
     * 登录
     *
     * @param userLoginDto
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDTO userLoginDto, HttpSession session) {
        User user = userService.login(userLoginDto);

        if (user == null) {
            return Result.error(MessageConstant.PASSWORD_ERROR);
        }

        // 如果 user 不为空，则获取 student 并存入 session
        Student student = userService.saveInfo(user);
        System.out.println(student+"有值吗");
        if (student != null) {
            System.out.println("不为空");
            session.setAttribute("student", student);  // 将用户信息保存到 session
        }
        session.setAttribute("user", user);  // 将用户信息保存到 session

        return Result.success(MessageConstant.ENTER_SYSTEM);
    }

    @GetMapping("/info")
    public Result info(HttpSession session) {
        User user = (User) session.getAttribute("user");
        return Result.success(user);
    }

    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpSession session) {
        session.invalidate();
        return Result.success();
    }


    /**
     * 根据fullname查询管理员信息
     *
     * @param userid
     * @return
     */
    @GetMapping("/{id}")
    public Result<UserLoginVO> getById(@PathVariable String userid) {
        User user = userService.getByUserid(userid);

        UserLoginVO userLoginVo = UserLoginVO.builder()
                .fullname(user.getFullname())
                .password(user.getPassword())
                .telephone(user.getTelephone())
                .build();
        return Result.success(userLoginVo);
    }

    /**
     * 修改管理员信息
     *
     * @param userLoginDTO
     * @return
     */
    @PutMapping
    public Result update(@RequestBody UserLoginDTO userLoginDTO) {
        userService.update(userLoginDTO);
        return Result.success();
    }
}
